package com.gzw.scm.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.gzw.scm.ConfigureLog4J;
import com.gzw.scm.MyApplication;
import com.gzw.scm.R;
import com.gzw.scm.UpdateManager;
import com.gzw.scm.base.BaseActivity;
import com.gzw.scm.bean.Constant;
import com.gzw.scm.bean.UserInfo;
import com.gzw.scm.utils.AppUtils;
import com.gzw.scm.utils.JsonUtil;
import com.gzw.scm.utils.T;
import com.gzw.scm.utils.TwitterRestClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cz.msebera.android.httpclient.Header;

/**
 * 登录页面
 * Created by Wangzhiqiang on 2016-06-10
 */
public class LoginActivity extends BaseActivity {

    private AutoCompleteTextView actv_userName;
    private EditText et_password;
    private Button btn_login,btn_remember;
    private Context mContext;
    private Toolbar toolbar;
    private final static String tag = "LoginActviity-->";
    private TextView tv_set_ip,tv_version;
    private boolean isRemember;
    private Logger log;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_login);
    }

    @Override
    protected void initViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        actv_userName = (AutoCompleteTextView) findViewById(R.id.actv_userName);
        et_password = (EditText) findViewById(R.id.et_password);
        btn_login = (Button) findViewById(R.id.btn_login);
        tv_set_ip = (TextView) findViewById(R.id.tv_set_ip);
        btn_remember =(Button)findViewById(R.id.btn_rem);
        tv_version=(TextView) findViewById(R.id.tv_version);
        //初始化 log
        log=Logger.getLogger(this.getClass());
    }

    @Override
    protected void initData() {
        mContext = this;
        toolbar.setTitle("登录");
        toolbar.setNavigationIcon(null);
        setSupportActionBar(toolbar);
        isRemember = MyApplication.isRemember();
        if(isRemember==true) {
            readUserContent();
            btn_remember.setBackgroundResource(R.mipmap.login_icon_sel);
        }

        tv_version.setText("版本号:"+AppUtils.getVersionName(mContext));
    }

    @Override
    protected void initEvents() {
        btn_login.setOnClickListener(v ->
          Loginerification()
        );
        tv_set_ip.setOnClickListener(new myOnClick());
        btn_remember.setOnClickListener(new myOnClick());
        getVersion();

    }

    class myOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.tv_set_ip:
                    Intent mIntent = new Intent();
                    mIntent.setClass(mContext, SetIpActivity.class);
                    startActivity(mIntent);
                    break;
                case R.id.btn_rem:
                    if(isRemember==false){
                        btn_remember.setBackgroundResource(R.mipmap.login_icon_sel);
                        saveRemember(true);
                        isRemember = true;
                    }else {
                        btn_remember.setBackgroundResource(R.mipmap.login_icon_nor);
                        saveRemember(false);
                        isRemember = false;
                    }
                    break;
                default:
                    break;
            }
        }
    }

    public void Loginerification() {

        actv_userName.setError(null);
        et_password.setError(null);
        String userName = actv_userName.getText().toString();
        String password = et_password.getText().toString();
        boolean cancel = false;
        View focusView = null;
        //判断密码是为空 或者太短
        if (TextUtils.isEmpty(password)) {
            et_password.setError(getString(R.string.error_invalid_password));
            focusView = et_password;
            cancel = true;
        }
        //判断账号是否为空 或者不符合规则
        if (TextUtils.isEmpty(userName)) {
            actv_userName.setError(getString(R.string.error_field_required));
            focusView = actv_userName;
            cancel = true;
        }
        if (cancel) {
            focusView.requestFocus();
        } else {
            login(userName, password);
        }
    }

    public void login(String userName, String password) {
        Map<String, String> map = new HashMap<>();
        map.put("username", userName);
        map.put("password", password);
        map.put("type","0");
        String json = JsonUtil.toJson(map);

        RequestParams requestParams = new RequestParams();
        requestParams.add("method", "aplogin");
        requestParams.add("json", json);

        TwitterRestClient.post(null, requestParams, new TextHttpResponseHandler() {
            @Override
            public void onStart() {
                Log.i(tag, "onStart====");
                btn_login.setText(getResources().getString(R.string.logining));
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String response) {
                btn_login.setText(getResources().getString(R.string.login));

                try {
                    if (response == null || response.length() == 0) {
                        showAlertDialog("连接异常");
                        return;
                    }

                    String zt = JsonUtil.getMsg(response, "status").toString();
                    if(zt.equals("1")){
                        String userinfo = JsonUtil.getMsg(response, "okMsg").toString();
                        Log.d("Debug", "onSuccess: "+userinfo);
                        UserInfo userInfo = JsonUtil.getPerson(userinfo, UserInfo.class);
                        saveUserContent(userInfo);
                        Intent mIntent = new Intent();
                        mIntent.setClass(mContext, MainActivity.class);
                        mIntent.putExtra("DepartmentType",userInfo.getDepartmentType());
                        startActivityForResult(mIntent, 1);// 请求码
                        finish();

                    }else if(zt.equals("2")){
                        String show = JsonUtil.getMsg(response, "errorId").toString();
                        T.showShort(mContext,show);
                    }else if(zt.equals("3")){
                        String show = JsonUtil.getMsg(response, "errorMsg").toString();
                        T.showShort(mContext,show);
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                    log.info("aplogin:"+e.toString()+"/respone="+response);
                    showAlertDialog(e.toString());
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String errorResponse, Throwable e) {
                Log.i(tag, "onFailure====");
                btn_login.setText(getResources().getString(R.string.login));
//                T.showShort(mContext, "登录异常" + e);
                showAlertDialog("登录异常" + e);
                log.info("aplogin:"+e.toString());
                Log.i(tag, "statusCode:" + statusCode + " headers:", e);
            }

            @Override
            public void onRetry(int retryNo) {
                btn_login.setText(getResources().getString(R.string.login));
                showAlertDialog("登录异常");
                Log.i(tag, "onRetry====");
                Log.i(tag, String.valueOf(retryNo));
            }
        });
    }


    private void saveUserContent(UserInfo userInfo) {
        SharedPreferences sharedPreferences = getSharedPreferences(Constant.USERINFO_KEY,
            Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        MyApplication.setUserInfo(userInfo);
        Log.d("Debug", "saveUserContent: "+userInfo.getId());
        edit.putInt(Constant.UAER_ID,userInfo.getId());
        edit.putString(Constant.USER_NAME_KEY, userInfo.getUsername());
        edit.putString(Constant.NAME_KEY, userInfo.getName());
        edit.putInt(Constant.DID_KEY, userInfo.getDid());
        edit.putInt(Constant.BELONGID, userInfo.getBelongId());
        edit.putInt(Constant.DEPARTMENTTYPE, userInfo.getDepartmentType());
        edit.putBoolean(Constant.IS_USER_LOGIN_KEY, true);
        edit.putString(Constant.DEPARTMENT_NAME,userInfo.getDepartment_name());
        edit.putString("passWord", et_password.getText().toString().trim());
        edit.apply();
}

    private void readUserContent() {
        SharedPreferences sharedPreferences = getSharedPreferences(Constant.USERINFO_KEY,
                Context.MODE_PRIVATE);
        UserInfo userInfo = new UserInfo();
        userInfo.setPassword(sharedPreferences.getString("passWord", ""));
        et_password.setText(userInfo.getPassword().toString().trim());
        actv_userName.setText(sharedPreferences.getString(Constant.USER_NAME_KEY, ""));
    }

    private void saveRemember(boolean isRemember){
        SharedPreferences sharedPreferences = getSharedPreferences(Constant.USERINFO_KEY,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putBoolean(Constant.REMEMBER, isRemember);
        edit.putString(Constant.USER_NAME_KEY,actv_userName.getText().toString().trim());
        edit.putString("passWord", et_password.getText().toString().trim());
        edit.commit();
    }

    private void getVersion(){
        String version = AppUtils.getVersionName(mContext);
        RequestParams requestParams = new RequestParams();
        requestParams.add("method", "getVersion");
        requestParams.put("ver",version);
        TwitterRestClient.post(null, requestParams, new TextHttpResponseHandler() {
            @Override
            public void onStart() {
                Log.i(tag, "onStart====");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String response) {

                try {
                    if (response == null || response.length() == 0) {
                        showAlertDialog("查询版本信息连接异常");
                        return;
                    }
                    if(response.contains("系统异常")){
                        showAlertDialog("网络异常");
                        return;
                    }
                    String zt = JsonUtil.getMsg(response, "jiaoyan").toString();
                    if(zt.equals("false")){
                        UpdateManager updateManager = new UpdateManager(mContext);
                        updateManager.checkUpdateInfo();
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                    log.info("getVersion:"+e.toString()+"/respone="+response);
                    showAlertDialog(e.toString());
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String errorResponse, Throwable e) {
                showAlertDialog("查询版本信息异常");
            }
        });
    }

}

